import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const docsRoot = path.join(__dirname, '../docs')

// 创建新的目录结构
const newStructure = {
  'typescript-docs': [
    // 这里添加TypeScript文档文件
    'typescript-guide.md',
    'typescript-exercises.md'
  ],
  'vue-component-docs': [
    // Vue组件文档
    'component-creation-guide.md',
    'component-communication.md',
    'component-design-patterns.md',
    'component-library-guide.md',
    'theme-customization-guide.md',
    'i18n-a11y-guide.md',
    'component-testing-guide.md',
    'component-documentation-guide.md',
    'learning-path.md',
    'USAGE-GUIDE.md',
    'DEVELOPMENT-SETUP.md',
    'DOCUMENTATION-TREE.md'
  ]
}

// 创建目录
function createDirectories() {
  for (const dir in newStructure) {
    const dirPath = path.join(docsRoot, dir)
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath, { recursive: true })
      console.log(`Created directory: ${dir}`)
    }
  }
}

// 移动文件到新位置
function moveFiles() {
  for (const dir in newStructure) {
    newStructure[dir].forEach(file => {
      const oldPath = path.join(docsRoot, file)
      const newPath = path.join(docsRoot, dir, file)
      
      if (fs.existsSync(oldPath)) {
        fs.renameSync(oldPath, newPath)
        console.log(`Moved: ${file} -> ${dir}/${file}`)
      } else {
        console.log(`File not found: ${file}`)
      }
    })
  }
}

// 更新文档助手配置
function updateDocsHelper() {
  const helperPath = path.join(__dirname, '../scripts/docs-helper.js')
  let content = fs.readFileSync(helperPath, 'utf8')
  
  // 更新文档路径
  content = content.replace(
    "const DOCS_DIR = path.join(__dirname, '../docs')",
    "const DOCS_DIR = path.join(__dirname, '../docs/vue-component-docs')"
  )
  
  // 更新文档索引
  const newIndex = `const DOC_INDEX = {
  'component-creation': 'component-creation-guide.md',
  'component-comm': 'component-communication.md',
  'design-patterns': 'component-design-patterns.md',
  'component-lib': 'component-library-guide.md',
  'theme': 'theme-customization-guide.md',
  'i18n': 'i18n-a11y-guide.md',
  'testing': 'component-testing-guide.md',
  'docs': 'component-documentation-guide.md',
  'learn': 'learning-path.md',
  'tree': 'DOCUMENTATION-TREE.md'
}`
  
  content = content.replace(/const DOC_INDEX = {[\s\S]*?}/, newIndex)
  fs.writeFileSync(helperPath, content, 'utf8')
  console.log('Updated docs-helper.js')
}

// 执行重组
function reorganizeDocs() {
  createDirectories()
  moveFiles()
  updateDocsHelper()
  console.log('Document reorganization completed!')
}

reorganizeDocs()